package com.xzx.flink.streamapi.window;

import com.xzx.flink.bean.ClickEvent;
import com.xzx.flink.streamapi.source.ClickSource;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.SlidingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.sql.Timestamp;
import java.util.HashSet;

/**
 * 每10秒的UV数,5秒输出一次
 *
 * @author xinzhixuan
 * @version V1.0.0
 * @date 2021/4/20
 **/
public class Window_03_EventTime_ProcessWindowFunction {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);


        env.addSource(new ClickSource())
                .assignTimestampsAndWatermarks(WatermarkStrategy.<ClickEvent>forMonotonousTimestamps()
                        .withTimestampAssigner(new SerializableTimestampAssigner<ClickEvent>() {
                            @Override
                            public long extractTimestamp(ClickEvent element, long recordTimestamp) {
                                return element.getTimestamp();
                            }
                        }))
                // 将数据全部发往同一分区，按窗口统计 UV
                .keyBy(x -> true)
                .window(SlidingEventTimeWindows.of(Time.seconds(10), Time.seconds(2)))
                .process(new ProcessWindowFunction<ClickEvent, String, Boolean, TimeWindow>() {
                    /**
                     * 关闭窗口的时候调用一次
                     * @param aBoolean The key for which this window is evaluated.
                     * @param context The context in which the window is being evaluated.
                     * @param elements The elements in the window being evaluated.
                     * @param out A collector for emitting elements.
                     * @throws Exception
                     */
                    @Override
                    public void process(Boolean aBoolean, ProcessWindowFunction<ClickEvent, String, Boolean, TimeWindow>.Context context, Iterable<ClickEvent> elements, Collector<String> out) throws Exception {
                        // UV信息
                        HashSet<String> users = new HashSet<>();
                        for (ClickEvent element : elements) {
                            users.add(element.getUser());
                        }
                        // 集合窗口信息
                        long start = context.window().getStart();
                        long end = context.window().getEnd();

                        out.collect("窗口：" + new Timestamp(start) + "~" + new Timestamp(end) + " 的UV数=" + users.size());
                    }
                })
                .print();

        env.execute();
    }
}
